package com.china08.yxyapi.service.sws.homeschool.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.mg.office.YxyNoticeClass;
import com.china08.yxyapi.service.sws.homeschool.YxyNoticeClassStatisticsService;
import com.china08.yxyapi.util.DateUtils;

@Service
public class YxyNoticeClassStatisticsServiceImpl implements YxyNoticeClassStatisticsService {

    private static final Logger LOGGER = Logger.getLogger(YxyNoticeClassStatisticsServiceImpl.class);

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据班级ClassId分组统计
     * 
     * @param day
     * @throws ParseException
     */
    @Override
    public void getNoticeClassForClass(Integer day) throws ParseException {

        boolean lastMonthStatisticsflag = false;

        Date dayDate = DateUtils.getBeforeDay(DateUtils.formatStrDate4(day));
        Date monthFirst = DateUtils.getMothOfFirstDay(dayDate);

        long dayCount = DateUtils.difference(dayDate, monthFirst);
        if (dayCount < 6) {
            lastMonthStatisticsflag = true;
        }

        // 统计上个月数据
        if (lastMonthStatisticsflag) {
            Date lastMonthDate = DateUtils.getBeforeDay(monthFirst);
            Date startlastMonthDate = DateUtils.getMothOfFirstDay(lastMonthDate);
            Date endlastMonthDate = DateUtils.getMothOfLastDay(lastMonthDate);

            Criteria criteria = Criteria.where("createdDate").gte(startlastMonthDate).lte(endlastMonthDate);

            TypedAggregation<YxyNoticeClass> aggregation = Aggregation.newAggregation(YxyNoticeClass.class,
                    Aggregation.match(criteria),
                    Aggregation.group("classId", "schoolId")//
                            .count().as("count")//
                            .sum("receiveRate").as("receiveRate")//
                            .first("classId").as("classId")//
                            .first("schoolId").as("schoolId"));

            AggregationResults<ClassNoticeClassModel> result = mongoTemplate.aggregate(aggregation,
                    ClassNoticeClassModel.class);
            List<ClassNoticeClassModel> classNoticeModelLst = result.getMappedResults();
            List<ClassNoticeClassModel> sendDataLst = new ArrayList<ClassNoticeClassModel>();

            Integer index = 0;
            for (ClassNoticeClassModel NoticeMode : classNoticeModelLst) {

                sendDataLst.add(NoticeMode);
                index++;
                if (index == 100) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("classNoticeClassModelLst", sendDataLst);
                        map.put("dateTime", DateUtils.formatDate6(lastMonthDate));
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String httpResult = restTemplate.postForObject(
                                yxyApiYxUrl + "/comm/school/sws/homeschool/class/noticeclass", formEntity,
                                String.class);
                        if (httpResult.contains("success")) {
                            System.out.println("getNoticeClassForClass方法执行ok,数据来源日期：" + day + "(上月)");
                        }
                    } catch (Exception e) {
                        LOGGER.info("getNoticeClassForClass方法执行错误：" + e.getMessage() + ",数据来源日期：" + day + "(上月)");
                    }
                    sendDataLst = new ArrayList<ClassNoticeClassModel>();
                    index = 0;
                }
            }
            if (sendDataLst.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("classNoticeClassModelLst", sendDataLst);
                    map.put("dateTime", DateUtils.formatDate6(lastMonthDate));
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/homeschool/class/noticeclass", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getNoticeClassForClass方法执行ok,数据来源日期：" + day + "(上月)");
                    }
                } catch (Exception e) {
                    LOGGER.info("getNoticeClassForClass方法执行错误：" + e.getMessage() + ",数据来源日期：" + day + "(上月)");
                }
            }
        }

        // 本月数据

        Date startDate = DateUtils.getMothOfFirstDay(dayDate);
        Date endDate = DateUtils.getMothOfLastDay(dayDate);

        Criteria criteria = Criteria.where("createdDate").gte(startDate).lte(endDate);

        TypedAggregation<YxyNoticeClass> aggregation = Aggregation.newAggregation(YxyNoticeClass.class,
                Aggregation.match(criteria),
                Aggregation.group("classId", "schoolId")//
                        .count().as("count")//
                        .sum("receiveRate").as("receiveRate")//
                        .first("classId").as("classId")//
                        .first("schoolId").as("schoolId"));

        AggregationResults<ClassNoticeClassModel> result = mongoTemplate.aggregate(aggregation,
                ClassNoticeClassModel.class);
        List<ClassNoticeClassModel> classNoticeModelLst = result.getMappedResults();
        List<ClassNoticeClassModel> sendDataLst = new ArrayList<ClassNoticeClassModel>();

        Integer index = 0;
        for (ClassNoticeClassModel NoticeMode : classNoticeModelLst) {

            sendDataLst.add(NoticeMode);
            index++;
            if (index == 100) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("classNoticeClassModelLst", sendDataLst);
                    map.put("dateTime", DateUtils.formatDate6(dayDate));
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/homeschool/class/noticeclass", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getNoticeClassForClass方法执行ok,数据来源日期：" + day);
                    }
                } catch (Exception e) {
                    LOGGER.info("getNoticeClassForClass方法执行错误：" + e.getMessage() + ",数据来源日期：" + day);
                }
                sendDataLst = new ArrayList<ClassNoticeClassModel>();
                index = 0;
            }
        }
        if (sendDataLst.size() > 0) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("classNoticeClassModelLst", sendDataLst);
                map.put("dateTime", DateUtils.formatDate6(dayDate));
                HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                String httpResult = restTemplate.postForObject(
                        yxyApiYxUrl + "/comm/school/sws/homeschool/class/noticeclass", formEntity, String.class);
                if (httpResult.contains("success")) {
                    System.out.println("getNoticeClassForClass方法执行ok,数据来源日期：" + day);
                }
            } catch (Exception e) {
                LOGGER.info("getNoticeClassForClass方法执行错误：" + e.getMessage() + ",数据来源日期：" + day);
            }
        }
    }

    protected static class ClassNoticeClassModel {
        public String classId;
        public String schoolId;

        public Long count;
        public Double receiveRate;
    }

    /**
     * 根据学校schoolId分组统计
     * 
     * @param day
     * @throws ParseException
     */
    @Override
    public void getNoticeClassForSchool(Integer day) throws ParseException {

        Date dayDate = DateUtils.getBeforeDay(DateUtils.formatStrDate4(day));

        for (int i = 6; i >= 0; i--) {
            Date lastDate = DateUtils.subtractDay(dayDate, i);

            Date startlastDate = DateUtils.getFirstDay(lastDate);
            Date endlastDate = DateUtils.getTimesnight(lastDate);

            Criteria criteria = Criteria.where("createdDate").gte(startlastDate).lte(endlastDate);

            TypedAggregation<YxyNoticeClass> aggregation = Aggregation.newAggregation(YxyNoticeClass.class,
                    Aggregation.match(criteria),
                    Aggregation.group("schoolId")//
                            .count().as("count")//
                            .sum("receiveRate").as("receiveRate")//
                            .first("schoolId").as("schoolId"));

            AggregationResults<SchoolNoticeClassModel> result = mongoTemplate.aggregate(aggregation,
                    SchoolNoticeClassModel.class);
            List<SchoolNoticeClassModel> schoolNoticeClassModelLst = result.getMappedResults();
            List<SchoolNoticeClassModel> sendDataLst = new ArrayList<SchoolNoticeClassModel>();

            Integer index = 0;
            for (SchoolNoticeClassModel schoolNotice : schoolNoticeClassModelLst) {

                sendDataLst.add(schoolNotice);
                index++;
                if (index == 100) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("schoolNoticeClassModelLst", sendDataLst);
                        map.put("dateTime", DateUtils.formatDate4(lastDate));
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String httpResult = restTemplate.postForObject(
                                yxyApiYxUrl + "/comm/school/sws/homeschool/school/noticeclass", formEntity,
                                String.class);
                        if (httpResult.contains("success")) {
                            System.out
                                    .println("getNoticeClassForSchool方法执行ok,数据来源日期：" + DateUtils.formatDate4(lastDate));
                        }
                    } catch (Exception e) {
                        LOGGER.info("getNoticeClassForSchool方法执行错误：" + e.getMessage() + ",数据来源日期："
                                + DateUtils.formatDate4(lastDate));
                    }
                    sendDataLst = new ArrayList<SchoolNoticeClassModel>();
                    index = 0;
                }
            }
            if (sendDataLst.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("schoolNoticeClassModelLst", sendDataLst);
                    map.put("dateTime", DateUtils.formatDate4(lastDate));
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/homeschool/school/noticeclass", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getNoticeClassForSchool方法执行ok,数据来源日期：" + DateUtils.formatDate4(lastDate));
                    }
                } catch (Exception e) {
                    LOGGER.info("getNoticeClassForSchool方法执行错误：" + e.getMessage() + ",数据来源日期："
                            + DateUtils.formatDate4(lastDate));
                }
            }
        }
    }

    protected static class SchoolNoticeClassModel {
        public String schoolId;

        public Long count;
        public Double receiveRate;
    }

    /**
     * 根据学校schoolId+用户userId分组统计
     * 
     * @param day
     * @throws ParseException
     */
    @Override
    public void getNoticeClassForUser(Integer day) throws ParseException {

        boolean lastMonthStatisticsflag = false;

        Date dayDate = DateUtils.getBeforeDay(DateUtils.formatStrDate4(day));
        Date monthFirst = DateUtils.getMothOfFirstDay(dayDate);

        long dayCount = DateUtils.difference(dayDate, monthFirst);
        if (dayCount < 6) {
            lastMonthStatisticsflag = true;
        }

        // 统计上个月数据
        if (lastMonthStatisticsflag) {
            Date lastMonthDate = DateUtils.getBeforeDay(monthFirst);
            Date startlastMonthDate = DateUtils.getMothOfFirstDay(lastMonthDate);
            Date endlastMonthDate = DateUtils.getMothOfLastDay(lastMonthDate);

            Criteria criteria = Criteria.where("createdDate").gte(startlastMonthDate).lte(endlastMonthDate);

            TypedAggregation<YxyNoticeClass> aggregation = Aggregation.newAggregation(YxyNoticeClass.class,
                    Aggregation.match(criteria),
                    Aggregation.group("userId", "schoolId")//
                            .count().as("count")//
                            .sum("receiveRate").as("receiveRate")//
                            .first("userId").as("userId")//
                            .first("nickName").as("nickName")//
                            .first("schoolId").as("schoolId"));

            AggregationResults<UserNoticeClassModel> result = mongoTemplate.aggregate(aggregation,
                    UserNoticeClassModel.class);
            List<UserNoticeClassModel> userNoticeClassModelLst = result.getMappedResults();
            List<UserNoticeClassModel> sendDataLst = new ArrayList<UserNoticeClassModel>();

            Integer index = 0;
            for (UserNoticeClassModel userNotice : userNoticeClassModelLst) {

                sendDataLst.add(userNotice);
                index++;
                if (index == 100) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("userNoticeClassModelLst", sendDataLst);
                        map.put("dateTime", DateUtils.formatDate6(lastMonthDate));
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String httpResult = restTemplate.postForObject(
                                yxyApiYxUrl + "/comm/school/sws/homeschool/user/noticeclass", formEntity, String.class);
                        if (httpResult.contains("success")) {
                            System.out.println("getNoticeClassForUser方法执行ok,数据来源日期：" + day + "上月");
                        }
                    } catch (Exception e) {
                        LOGGER.info("getNoticeClassForUser方法执行错误：" + e.getMessage() + ",数据来源日期：" + day + "上月");
                    }
                    sendDataLst = new ArrayList<UserNoticeClassModel>();
                    index = 0;
                }
            }
            if (sendDataLst.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("userNoticeClassModelLst", sendDataLst);
                    map.put("dateTime", DateUtils.formatDate6(lastMonthDate));
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/homeschool/user/noticeclass", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getNoticeClassForUser方法执行ok,数据来源日期：" + day + "上月");
                    }
                } catch (Exception e) {
                    LOGGER.info("getNoticeClassForUser方法执行错误：" + e.getMessage() + ",数据来源日期：" + day + "上月");
                }
            }
        }

        // 本月数据

        Date startDate = DateUtils.getMothOfFirstDay(dayDate);
        Date endDate = DateUtils.getMothOfLastDay(dayDate);

        Criteria criteria = Criteria.where("createdDate").gte(startDate).lte(endDate);

        TypedAggregation<YxyNoticeClass> aggregation = Aggregation.newAggregation(YxyNoticeClass.class,
                Aggregation.match(criteria),
                Aggregation.group("userId", "schoolId")//
                        .count().as("count")//
                        .sum("receiveRate").as("receiveRate")//
                        .first("userId").as("userId")//
                        .first("nickName").as("nickName")//
                        .first("schoolId").as("schoolId"));

        AggregationResults<UserNoticeClassModel> result = mongoTemplate.aggregate(aggregation,
                UserNoticeClassModel.class);
        List<UserNoticeClassModel> userNoticeClassModelLst = result.getMappedResults();
        List<UserNoticeClassModel> sendDataLst = new ArrayList<UserNoticeClassModel>();

        Integer index = 0;
        for (UserNoticeClassModel userNotice : userNoticeClassModelLst) {

            sendDataLst.add(userNotice);
            index++;
            if (index == 100) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("userNoticeClassModelLst", sendDataLst);
                    map.put("dateTime", DateUtils.formatDate6(dayDate));
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/homeschool/user/noticeclass", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getNoticeClassForUser方法执行ok,数据来源日期：" + day + "上月");
                    }
                } catch (Exception e) {
                    LOGGER.info("getNoticeClassForUser方法执行错误：" + e.getMessage() + ",数据来源日期：" + day + "上月");
                }
                sendDataLst = new ArrayList<UserNoticeClassModel>();
                index = 0;
            }
        }
        if (sendDataLst.size() > 0) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("userNoticeClassModelLst", sendDataLst);
                map.put("dateTime", DateUtils.formatDate6(dayDate));
                HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                String httpResult = restTemplate.postForObject(
                        yxyApiYxUrl + "/comm/school/sws/homeschool/user/noticeclass", formEntity, String.class);
                if (httpResult.contains("success")) {
                    System.out.println("getNoticeClassForUser方法执行ok,数据来源日期：" + day + "上月");
                }
            } catch (Exception e) {
                LOGGER.info("getNoticeClassForUser方法执行错误：" + e.getMessage() + ",数据来源日期：" + day + "上月");
            }
        }
    }

    protected static class UserNoticeClassModel {
        public String userId;
        public String nickName;
        public String schoolId;

        public Long count;
        public Double receiveRate;
    }

}
